<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j store-signate-page-container">
    <div
      v-if="config.storeStyle === 0"
      class="store-top-container"
      :style="{background: config.bgUrl !== '' ? `url(${config.bgUrl}) no-repeat` : '#fff'}"
    >
      <div class="store-top style1">
        <img
          class="logo-img"
          :src="checkFileUrl(requestShop.shopLogo)"
          alt=""
        >
        <span class="store-name">{{ requestShop.shopName }}</span>
        <span class="custom-store">
          {{ shopInfo.shopId === 1 ? $t('shopInfo.selfShop') : getStoreType(requestShop.type) }}
        </span>
        <p
          style="padding-top: 2px;"
          @click="toChatIm"
        >
          <img
            src="@/assets/images/connect_customer.png"
            alt=""
          >
          <span>{{ $t('prodDetail.contactCustomerService') }}</span>
        </p>
        <p
          class="favourite"
          :class="{ active: isclickCollection }"
          @click="shopCollection()"
        >
          <i class="icon" />
          <span>{{ $t('prodDetail.collectionStores') }}</span>
        </p>
        <p
          class="favourite"
          @click="onToQualifications()"
        >
          <img
            src="@/assets/images/qualifications.png"
            style="width: 16px;height: 16px;"
          >
          <span>{{ $t('shopInfo.qualifications') }}</span>
        </p>
      </div>
    </div>
    <div
      v-if="config.storeStyle === 1"
      class="store-top style2"
    >
      <div class="store-top-content">
        <span class="custom-store">{{ getStoreType(requestShop.type) }}</span>
        <span class="store-name">{{ requestShop.shopName }}</span>
        <p
          style="padding-top: 2px;"
          @click="toChatIm"
        >
          <img
            src="@/assets/images/connect_customer.png"
            alt=""
          >
          <span>{{ $t('prodDetail.contactCustomerService') }}</span>
        </p>
        <p
          class="favourite"
          :class="{ active: isclickCollection}"
          @click="shopCollection()"
        >
          <i class="icon" />
          <span>{{ $t('prodDetail.collectionStores') }}</span>
        </p>
        <p
          class="favourite"
          @click="onToQualifications()"
        >
          <img
            src="@/assets/images/qualifications.png"
            style="width: 16px;height: 16px;"
          >
          <span>{{ $t('shopInfo.qualifications') }}</span>
        </p>
      </div>
      <div
        v-if="config.bgUrl !== ''"
        class="store-top-bottom"
        :style="{background: config.bgUrl !== '' ? `url(${config.bgUrl}) no-repeat` : '#fff'}"
      />
    </div>
    <div
      v-if="config.showNavs === 0"
      class="store-bottom"
      :style="{background: config.navsBg}"
    >
      <div class="bottom-content">
        <div class="navs-list">
          <li
            v-if="config.showCategory === 0"
            class="category-items"
            @mouseover="categoryMouser"
            @mouseleave="categoryMouseLeave"
          >
            <span @click="handleAllCategory">{{ $t('shopInfo.allCategories') }}</span>
            <el-icon v-if="showCategoryStatus">
              <CaretTop />
            </el-icon>
            <el-icon v-else>
              <CaretBottom />
            </el-icon>
            <!-- 全部分类下拉 start -->
            <div
              v-show="showCategoryStatus"
              class="all-category-container"
            >
              <template
                v-for="(item, index) in categoryList"
                :key="index"
              >
                <div

                  class="all-category-item"
                  @click="getProdListByCategory(item.categoryId)"
                >
                  {{ item.categoryName }}
                </div>
              </template>
            </div>
            <!-- 全部分类下拉 end -->
          </li>
          <li
            v-if="config.announcement === 0"
            @click="handleAnnount"
          >
            {{ $t('announcement') }}
          </li>
          <template v-if="config.showNavs === 0">
            <template
              v-for="(item, index) in config.navList"
              :key="index"
            >
              <li

                @click="handleItems(item)"
              >
                {{ item.name }}
              </li>
            </template>
          </template>
        </div>
        <div
          v-show="config.search === 0"
          class="search-content"
        >
          <input v-model.trim="searchText">
          <img
            src="@/assets/images/search-content.png"
            alt
          >
          <div
            class="search-btn"
            @click="handleSearch"
          >
            {{ $t('collection.Search') }}
          </div>
        </div>
      </div>
    </div>
    <!-- 登录弹窗组件 -->
    <login-popup
      v-if="showLogin"
      @hide-login-pop="hideLoginPop"
    />
    <!-- /登录弹窗组件 -->
  </div>
</template>
<script setup>
import { redirectPath } from '../common/pageConfig.js'
import Cookie from 'vue-cookies'
import { ElMessage } from 'element-plus'
import { checkFileUrl } from '@/utils/index.js'

const props = defineProps({
  shopInfo: { // 店铺信息
    type: Object,
    default: () => {
    }
  },
  decorateHeader: { // 商家导航
    type: Array,
    default: () => []
  },
  isCollection: { // 用户是否收藏店铺
    type: Boolean,
    default: () => false
  },
  categoryList: { // 分类
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['handleSearchData'])

const route = useRoute()
const router = useRouter()
const langStore = useLanguageStore()

const getStoreType = computed(() => {
  // 店铺类型
  return (type) => {
    if (type === 0) {
      return '普通店铺'
    } else if (type === 1) {
      return '优选好店'
    } else {
      return ''
    }
  }
})

const getCategoryRoute = computed(() => {
  // 获取路由的变化
  return langStore.shopRoutes
})

const config = ref({})
watch(() => props.decorateHeader, (newVal) => {
  if (Array.isArray(newVal) && newVal.length > 0) {
    config.value = {
      storeStyle: newVal[0].storeStyle, // 店铺信息样式类型
      showCategory: newVal[0].showCategory, // 全部分类是否显示
      showNavs: newVal[0].showNavs, // 导航栏是否显示
      navsBg: newVal[0].navsBg, // 导航栏背景
      search: newVal[0].search, // 搜索
      announcement: newVal[0].announcement, // 公告
      navList: newVal[0].navList, // 导航栏个数
      bgUrl: newVal[0].bgUrl // 图片背景
    }
  } else {
    config.value = {}
  }
}, { immediate: true, deep: true })

const isclickCollection = ref(false) // 是否收藏
watch(() => props.isCollection, (val) => {
  isclickCollection.value = val
}, { immediate: true })

watch(() => getCategoryRoute.value, (val) => {
  // 监听路由
  const { cid } = val
  if (cid) {
    getProdListByCategory(cid)
  }
})

const searchText = ref('') // 搜索关键词
onMounted(() => {
  // 获取店铺信息
  getShopMessage()
  const { pn, cid } = route.query
  if (pn || cid) {
    searchText.value = pn
    getProdListByCategory(cid)
  }
})

const requestShop = ref({}) // 获取店铺信息
// 获取店铺信息
const getShopMessage = () => {
  const { sid } = route.query
  http.get('/shop/headInfo', {
    params: {
      shopId: sid
    }
  }).then(res => {
    requestShop.value = res.data
  })
}

// 公告
const handleAnnount = () => {
  router.push({
    path: '/notice-list',
    query: {
      shopId: props.shopInfo.shopId,
      shopName: props.shopInfo.shopName
    }
  })
}

// 导航跳转
const handleItems = (item) => {
  if (item.path.type === '4') { // 表示跳转的页面
    if (item.path.link.toString().indexOf('/shop-index') !== -1) {
      const params = new URLSearchParams(item.path.link.split('?')[1])
      const sid = params.get('sid')
      router.push({
        path: '/shop-index',
        query: { sid }
      })
      emit('handleSearchData', { type: 'none' })
    } else {
      redirectPath(router, item)
    }
  } else {
    if (item.path.type === '1') { // 跳转到商品详情
      const newPage = router.resolve({ path: '/detail', query: { prodId: item.path.link } })
      window.open(newPage.href, '_blank', 'noopener,noreferrer')
    } else if (item.path.type === '2') { // 跳转分类
      getProdListByCategory(item.path.link.categoryId)
    } else if (item.path.type === '5') { // 跳转微页面
      router.push({
        path: '/select-decorate',
        query: {
          renovationId: item.path.link[0],
          sid: item.path.link[1]
        }
      })
      emit('handleSearchData', { type: 'none' })
    } else {
      redirectPath(router, item)
    }
  }
}

/**
 * 收藏店铺/取消收藏
 */
const shopCollection = () => {
  http
    .post('/p/shop/collection/addOrCancel', props.shopInfo.shopId)
    .then(({ data }) => {
      isclickCollection.value = data
      if (data) {
        ElMessage({
          message: $t('prodDetail.collectionSuccess'),
          type: 'success',
          duration: 1000
        })
      } else {
        ElMessage({
          message: $t('prodDetail.uncollected'),
          duration: 1000
        })
      }
    })
}

const showLogin = ref(false) // 登录弹窗是否显示
/**
 * 隐藏登录弹窗
 */
const hideLoginPop = () => {
  showLogin.value = false
  if (route.path.indexOf('user-center') > -1) {
    router.push({ path: '/' })
  }
}

// 跳转商家客服
const toChatIm = () => {
  if (Cookie.get('bbcToken')) {
    const routeUrl = router.resolve({
      path: '/chat',
      query: {
        shopId: props.shopInfo.shopId
      }
    })
    window.open(routeUrl.href, 'view_window')
  } else {
    showLogin.value = true
  }
}

const showCategoryStatus = ref(false) // 全部分类下拉是否显示
// 鼠标移入分类
const categoryMouser = () => {
  showCategoryStatus.value = true
}
// 鼠标移除分类
const categoryMouseLeave = () => {
  showCategoryStatus.value = false
}

let searchData = {} // 查询的数据或者分类的数据
const categoryId = ref('') // 分类id
// 查询
const handleSearch = async () => {
  const res = await searchGoodsData(searchText.value, categoryId.value)
  searchData = {
    type: res.type,
    category: res.category,
    data: res.data.records[0].products
  }
  emit('handleSearchData', searchData)
}

// 查询该分类下的商品
const getProdListByCategory = async (categoryIdPar, types) => {
  categoryId.value = categoryIdPar
  const res = await searchGoodsData(searchText.value, categoryId.value)
  searchData = {
    type: res.type,
    category: res.category,
    data: res.data.records[0].products
  }
  if (types) {
    searchData.type = types
    searchData.category = '热卖商品'
  }
  emit('handleSearchData', searchData)
}

// 查询商品接口
const searchGoodsData = (keywordPar, categoryIdPar) => {
  const { sid } = route.query
  return new Promise((resolve) => {
    http.get('/search/page', {
      params: {
        sort: 12,
        size: 20,
        current: 1,
        shopId: props.shopInfo.shopId,
        couponId: '',
        keyword: keywordPar, // 搜索关键词
        shopCategoryId: categoryIdPar, // 分类id
        isAllProdType: true,
        isActive: 1
      }
    }).then(res => {
      let path
      let type
      let categoryName = ''
      if (keywordPar && categoryIdPar) {
        type = 'category'
        path = {
          path: '/shop-prod-list',
          query: {
            sid,
            c: 1,
            pn: keywordPar,
            cid: categoryIdPar
          }
        }
      } else if (keywordPar && !categoryIdPar) {
        type = 'goods'
        path = {
          path: '/shop-prod-list',
          query: {
            sid,
            c: 1,
            pn: keywordPar
          }
        }
      } else if (!keywordPar && categoryIdPar) {
        type = 'category'
        path = {
          path: '/shop-prod-list',
          query: {
            sid,
            cid: categoryIdPar
          }
        }
      } else {
        type = 'none'
        path = {
          path: route.path,
          query: {
            sid
          }
        }
      }
      props.categoryList.forEach(item => {
        if (Number(item.categoryId) === Number(categoryIdPar)) {
          categoryName = item.categoryName
        }
      })
      router.push(path)
      resolve({
        type,
        category: categoryName,
        data: res.data
      })
    })
  })
}

// 全部分类点击
const handleAllCategory = () => {
  getProdListByCategory('', 'category')
}

/**
 * 去往 资质证照 页面
 */
const onToQualifications = () => {
  const { sid } = route.query
  router.push({
    path: '/shop-qualifications',
    query: {
      sid
    }
  })
}
</script>
<style lang="scss" scoped>
@use "index";
</style>
